import $http from '@/common/api/request.js';
export default {
	// 存储数据
	state:{
		list:[],
		// 选择的列表
		selectedList:[],
		// 存储list列表长度
		listLength:'1'
	},
	getters:{
		// 判断是否全选
		checkedAll(state){
			return state.list.length === state.selectedList.length;
			console.log(state.list);
		},
		// 计算list长度
		listLength(state){
			return state.listLength = state.list.length
		},
		// 计算selectedList长度
		selectedList(state){
			return state.selectedList.length;
		},
		//合计+结算数量
		totalCount(state){
			let total = {
				pprice:0,
				num:0
			}
			state.list.forEach(v=>{
				//是否选中
				if(state.selectedList.indexOf(v.id) > -1){
					//合计
					total.pprice += v.pprice*v.num;
					//结算数量
					total.num = state.selectedList.length;
				}
			})
			return total;
		}
	},
	mutations:{
		// 将获取到的数据复制给list
		initGetData(state,list){
			state.list = list
		},
		// 全选
		checkAll(state){
			state.selectedList = state.list.map(v=>{
				// 添加一个checked属性
				v.checked = true
				return v.id
			})
		},
		// 全不选
		unCheckAll(state){
			state.list.forEach(v=>{
				v.checked = false
			})
			state.selectedList = []
		},
		// 单选
		selectedItem(state,index){
			// 获取列表对象id
			let id = state.list[index].id
			// 根据id拿到selectedList列表中该id的下标
			let i = state.selectedList.indexOf(id)
			//如果selectedList已经存在就代表他之前是选中状态, checked=false,并且在selectedList删除
			if(i > -1){
				state.list[index].checked = false
				return state.selectedList.splice(i,1)
			}
			// 如果之前没有选中，checked=true,把当前的id添加到selectedList中
			state.list[index].checked = true;
			state.selectedList.push(id)
		},
		// 删除
		delGoods(state){
			state.list = state.list.filter(v=>{
				return state.selectedList.indexOf(v.id)
			})
		},
		// 加入购物车
		addShopCart(state,goods){
			goods.forEach((item,index)=>{
				state.list.push(item)
			})
		},
		totalCountMu(state,getters){
			console.log(state.list);
		},
		// 清除vuexstate数据
		clearState(state,goods){
			return state.list = []
		}
	},
	actions:{
		checkedAllFn({commit,getters}){
			
			getters.checkedAll  ?  commit("unCheckAll")  :  commit("checkAll");
		},
		delGoodsFn({commit,state}){
			uni.showModal({
				content:'确定删除吗?',
				success: () => {
					$http.request({
						url:"/deleteCart",
						method:"POST",
						header:{
							token:true
						},
						data:{
							goodsId:state.selectedList
						}
					}).then((res)=>{
						
						commit('delGoods');
						commit('unCheckAll');
						
						uni.showToast({
							title:'删除成功',
							icon:"none"
						})
						
					}).catch(()=>{
						uni.showToast({
							title:'请求失败',
							icon:'none'
						})
					})
				}
			})
		},
		totalCountFn({commit,getters}){
			commit('totalCountMu')
		}
	}
}